using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using ExamPaperEditingSystem.Models;
using ExamPaperEditingSystem.Services;
using ExamPaperEditingSystem.Utils;

namespace ExamPaperEditingSystem.ViewModels
{
    /// <summary>
    /// AI配置窗口ViewModel
    /// </summary>
    public class AIConfigurationViewModel : INotifyPropertyChanged
    {
        private readonly IConfigurationService _configurationService;
        private readonly Window _window;
        private AIConfiguration _configuration;
        private string _onlineApiStatus = "未测试";
        private string _localApiStatus = "未测试";
        private bool _isTesting = false;

        public AIConfigurationViewModel(IConfigurationService configurationService, Window window)
        {
            _configurationService = configurationService;
            _window = window;
            _configuration = AIConfiguration.CreateDefault();

            InitializeCommands();
            LoadConfigurationAsync();
        }

        #region Properties

        public string ChatApiUrl
        {
            get => _configuration.ChatApiUrl;
            set
            {
                _configuration.ChatApiUrl = value;
                OnPropertyChanged();
            }
        }

        public string EmbeddingApiUrl
        {
            get => _configuration.EmbeddingApiUrl;
            set
            {
                _configuration.EmbeddingApiUrl = value;
                OnPropertyChanged();
            }
        }

        public string LocalChatApiUrl
        {
            get => _configuration.LocalChatApiUrl;
            set
            {
                _configuration.LocalChatApiUrl = value;
                OnPropertyChanged();
            }
        }

        public string LocalEmbeddingApiUrl
        {
            get => _configuration.LocalEmbeddingApiUrl;
            set
            {
                _configuration.LocalEmbeddingApiUrl = value;
                OnPropertyChanged();
            }
        }

        public string ChatModel
        {
            get => _configuration.ChatModel;
            set
            {
                _configuration.ChatModel = value;
                OnPropertyChanged();
            }
        }

        public string LocalChatModel
        {
            get => _configuration.LocalChatModel;
            set
            {
                _configuration.LocalChatModel = value;
                OnPropertyChanged();
            }
        }

        public string EmbeddingModel
        {
            get => _configuration.EmbeddingModel;
            set
            {
                _configuration.EmbeddingModel = value;
                OnPropertyChanged();
            }
        }

        public double Temperature
        {
            get => _configuration.Temperature;
            set
            {
                _configuration.Temperature = value;
                OnPropertyChanged();
            }
        }

        public int MaxTokens
        {
            get => _configuration.MaxTokens;
            set
            {
                _configuration.MaxTokens = value;
                OnPropertyChanged();
            }
        }

        public int RequestTimeout
        {
            get => _configuration.RequestTimeout;
            set
            {
                _configuration.RequestTimeout = value;
                OnPropertyChanged();
            }
        }

        public int RetryCount
        {
            get => _configuration.RetryCount;
            set
            {
                _configuration.RetryCount = value;
                OnPropertyChanged();
            }
        }

        public bool UseLocalApiFirst
        {
            get => _configuration.UseLocalApiFirst;
            set
            {
                _configuration.UseLocalApiFirst = value;
                OnPropertyChanged();
            }
        }

        public bool EnableProxy
        {
            get => _configuration.EnableProxy;
            set
            {
                _configuration.EnableProxy = value;
                OnPropertyChanged();
            }
        }

        public string ProxyAddress
        {
            get => _configuration.ProxyAddress;
            set
            {
                _configuration.ProxyAddress = value;
                OnPropertyChanged();
            }
        }

        public int ProxyPort
        {
            get => _configuration.ProxyPort;
            set
            {
                _configuration.ProxyPort = value;
                OnPropertyChanged();
            }
        }

        public string ProxyUsername
        {
            get => _configuration.ProxyUsername;
            set
            {
                _configuration.ProxyUsername = value;
                OnPropertyChanged();
            }
        }

        public string ProxyPassword
        {
            get => _configuration.ProxyPassword;
            set
            {
                _configuration.ProxyPassword = value;
                OnPropertyChanged();
            }
        }

        public string OnlineApiStatus
        {
            get => _onlineApiStatus;
            set
            {
                _onlineApiStatus = value;
                OnPropertyChanged();
            }
        }

        public string LocalApiStatus
        {
            get => _localApiStatus;
            set
            {
                _localApiStatus = value;
                OnPropertyChanged();
            }
        }

        public bool IsTesting
        {
            get => _isTesting;
            set
            {
                _isTesting = value;
                OnPropertyChanged();
            }
        }

        #endregion

        #region Commands

        public ICommand TestOnlineApiCommand { get; private set; } = null!;
        public ICommand TestLocalApiCommand { get; private set; } = null!;
        public ICommand TestAllConnectionsCommand { get; private set; } = null!;
        public ICommand ResetDefaultCommand { get; private set; } = null!;
        public ICommand SaveCommand { get; private set; } = null!;
        public ICommand CancelCommand { get; private set; } = null!;

        private void InitializeCommands()
        {
            TestOnlineApiCommand = new RelayCommand(async () => await TestOnlineApiAsync(), () => !IsTesting);
            TestLocalApiCommand = new RelayCommand(async () => await TestLocalApiAsync(), () => !IsTesting);
            TestAllConnectionsCommand = new RelayCommand(async () => await TestAllConnectionsAsync(), () => !IsTesting);
            ResetDefaultCommand = new RelayCommand(async () => await ResetDefaultAsync());
            SaveCommand = new RelayCommand(async () => await SaveAsync());
            CancelCommand = new RelayCommand(() => _window.DialogResult = false);
        }

        #endregion

        #region Methods

        private async void LoadConfigurationAsync()
        {
            try
            {
                _configuration = await _configurationService.GetAIConfigurationAsync();
                OnPropertyChanged(string.Empty); // 刷新所有属性
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载配置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task TestOnlineApiAsync()
        {
            IsTesting = true;
            OnlineApiStatus = "测试中...";

            try
            {
                var chatResult = await _configurationService.TestApiConnectionAsync(ChatApiUrl, false);
                var embeddingResult = await _configurationService.TestApiConnectionAsync(EmbeddingApiUrl, true);

                if (chatResult && embeddingResult)
                {
                    OnlineApiStatus = "✓ 连接成功";
                }
                else if (chatResult)
                {
                    OnlineApiStatus = "⚠ 聊天API连接成功，嵌入API失败";
                }
                else if (embeddingResult)
                {
                    OnlineApiStatus = "⚠ 嵌入API连接成功，聊天API失败";
                }
                else
                {
                    OnlineApiStatus = "✗ 连接失败";
                }
            }
            catch (Exception ex)
            {
                OnlineApiStatus = $"✗ 测试失败: {ex.Message}";
            }
            finally
            {
                IsTesting = false;
            }
        }

        private async Task TestLocalApiAsync()
        {
            IsTesting = true;
            LocalApiStatus = "测试中...";

            try
            {
                var chatResult = await _configurationService.TestApiConnectionAsync(LocalChatApiUrl, false);
                var embeddingResult = await _configurationService.TestApiConnectionAsync(LocalEmbeddingApiUrl, true);

                if (chatResult && embeddingResult)
                {
                    LocalApiStatus = "✓ 连接成功";
                }
                else if (chatResult)
                {
                    LocalApiStatus = "⚠ 聊天API连接成功，嵌入API失败";
                }
                else if (embeddingResult)
                {
                    LocalApiStatus = "⚠ 嵌入API连接成功，聊天API失败";
                }
                else
                {
                    LocalApiStatus = "✗ 连接失败";
                }
            }
            catch (Exception ex)
            {
                LocalApiStatus = $"✗ 测试失败: {ex.Message}";
            }
            finally
            {
                IsTesting = false;
            }
        }

        private async Task TestAllConnectionsAsync()
        {
            await TestOnlineApiAsync();
            await TestLocalApiAsync();
        }

        private async Task ResetDefaultAsync()
        {
            var result = MessageBox.Show("确定要重置为默认配置吗？这将丢失当前所有设置。", 
                "确认重置", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    await _configurationService.ResetToDefaultAsync();
                    _configuration = AIConfiguration.CreateDefault();
                    OnPropertyChanged(string.Empty); // 刷新所有属性
                    OnlineApiStatus = "未测试";
                    LocalApiStatus = "未测试";
                    MessageBox.Show("配置已重置为默认值", "重置成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"重置配置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private async Task SaveAsync()
        {
            try
            {
                await _configurationService.SaveAIConfigurationAsync(_configuration);
                MessageBox.Show("配置保存成功", "保存成功", MessageBoxButton.OK, MessageBoxImage.Information);
                _window.DialogResult = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存配置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
